package artid.com.arttogo.view;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：实现对特定内容改变字体颜色的TextView   
 * 创建人：耿卫斌 
 * 使用方式：<com.zaime.kuaidiyuan.util.ChangeColorTextView_Util 
        				android:layout_width="match_parent"
        				android:layout_height="wrap_content"
        				android:text="详细地址"
        				/>
 					textView = (MyTextView)findViewById(R.id.tv);
        			textView.setSpecifiedTextsColor(text, "要改变的字（例如Android）", Color.parseColor("#FF0000"));
 */
public class ChangeColorTextView extends TextView
{

	public ChangeColorTextView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	public void setSpecifiedTextsColor(String text, String specifiedTexts, int color)
	{   
		List<Integer> sTextsStartList = new ArrayList<Integer>();

		int sTextLength = specifiedTexts.length();
		String temp = text;
		int lengthFront = 0;//记录被找出后前面的字段的长度
		int start = -1;
		do
		{
			start = temp.indexOf(specifiedTexts);

			if(start != -1)
			{
				start = start + lengthFront;
				sTextsStartList.add(start);
				lengthFront = start + sTextLength;
				temp = text.substring(lengthFront);
			}

		}while(start != -1);

		SpannableStringBuilder styledText = new SpannableStringBuilder(text);
		for(Integer i : sTextsStartList)
		{
			styledText.setSpan(
					new ForegroundColorSpan(color),
					i, 
					i + sTextLength, 
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		setText(styledText);
	}
}